//go:build windows
// +build windows

/*
@auther fenglei
*/
package xxsys

import (
	"fmt"
	"gitee.com/fenglei-l/ops-util/xxlog"
	"github.com/gogf/gf/v2/os/gproc"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gookit/goutil/sysutil/process"
	"strings"
	"syscall"
)

func ProcessGetId(name string) int {
	return process.PIDByName(name)
}
func ProcessKillPid(pid int) error {
	return process.Kill(pid, syscall.SIGKILL)
}
func ProcessNameId(name string) string {
	command := fmt.Sprintf("netstat -ano | findstr %s", name)
	output, err := ExecCmdSh(command)
	if err != nil {
		xxlog.ErrorUp366(fmt.Errorf(output, err))
		return ""
	}
	pid := ""
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		if strings.Contains(line, "LISTENING") && strings.Contains(line, name) {
			fields := strings.Fields(line)
			pid = fields[len(fields)-1]
		}
	}
	return pid
}
func ProcessKill(pid string) error {
	str := strings.Split(pid, "\n")
	for _, k := range str {
		if k != "" {
			m := gproc.NewManager()
			m.AddProcess(gconv.Int(k))
			m.KillAll()
			m.WaitAll()
			xxlog.InfoUp366("%s was killed", k)
		}
	}
	return nil
}
